package com.fenghuajueli.libbasecoreui.viewmodel;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.viewbinding.ViewBinding;

import com.fenghuajueli.libbasecoreui.mvp.BaseActivity;
import com.fenghuajueli.libbasecoreui.viewmodel.data.LoadingData;

public abstract class BaseViewModelActivity<T extends BaseViewModel, B extends ViewBinding> extends BaseActivity {

    /**
     * 创建这个页面的viewmodel
     *
     * @return
     */
    protected abstract T createViewModel();

    /**
     * 返回这个页面的viewbinding对象
     *
     * @return
     */
    protected abstract B createViewBinding();

    /**
     * view初始化成功
     */
    protected abstract void initView();

    /**
     * 注册通用的ui改变监听使用
     */
    protected T model;

    protected B binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = createViewBinding();
        if (binding == null) {
            throw new NullPointerException("binding is must not be null");
        }
        setContentView(binding.getRoot());
        model = createViewModel();
        if (model != null) {
            model.loadingViewData.observe(this, new Observer<LoadingData>() {
                @Override
                public void onChanged(LoadingData data) {
                    switch (data.getStatus()) {
                        case LoadingData.LOADING_START:
                            showLoadingDialog(data.getLoadingTips());
                            break;
                        case LoadingData.LOADING_STOP:
                            hideLoadingDialog();
                            break;
                    }
                }
            });
            model.finishActivityData.observe(this, new Observer<Integer>() {
                @Override
                public void onChanged(Integer integer) {
                    finish();
                }
            });
        } else {
            throw new NullPointerException("ViewModel is must not be null");
        }
        initView();
    }


}
